package com.qiaoba.module.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.module.system.converter.SysDictConverter;
import com.qiaoba.module.system.entity.SysDictType;
import com.qiaoba.module.system.entity.dto.SysDictTypeDTO;
import com.qiaoba.module.system.entity.param.SysDictTypeParam;
import com.qiaoba.module.system.mapper.SysDictTypeMapper;
import com.qiaoba.module.system.service.SysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典类型 服务层实现
 *
 * @author ailanyin
 * @date 2023-09-10 17:08:36
 */
@Service
@RequiredArgsConstructor
public class SysDictTypeServiceImpl implements SysDictTypeService {

    private final SysDictTypeMapper sysDictTypeMapper;

    @Override
    public int insert(SysDictTypeDTO dto) {
        checkDictTypeUnique(dto.getDictId(), dto.getDictType());
        return sysDictTypeMapper.insert(SysDictConverter.dto2Entity(dto));
    }

    @Override
    public int updateById(SysDictTypeDTO dto) {
        // 禁止修改 dictType
        dto.setDictType(null);
        checkDictTypeUnique(dto.getDictId(), dto.getDictType());
        return sysDictTypeMapper.updateById(SysDictConverter.dto2Entity(dto));
    }

    @Override
    public int deleteByIds(List<String> ids) {
        checkAllowDelete(ids);
        return sysDictTypeMapper.deleteBatchIds(ids);
    }

    @Override
    public SysDictType selectById(String dictId) {
        return sysDictTypeMapper.selectById(dictId);
    }

    @Override
    public List<SysDictType> selectList(SysDictTypeParam param) {
        return sysDictTypeMapper.selectList(SysDictConverter.param2Wrapper(param));
    }

    private void checkDictTypeUnique(String dictId, String dictType) {
        if (StrUtil.isNotBlank(sysDictTypeMapper.checkDictTypeUnique(dictId, dictType))) {
            throw new ServiceException(StrUtil.format("字典类型【{}】已存在", dictType));
        }
    }

    private void checkAllowDelete(List<String> ids) {
        String typeName = sysDictTypeMapper.checkAllowDelete(ids);
        if (StrUtil.isNotBlank(typeName)) {
            throw new ServiceException(StrUtil.format("字典类型【{}】存在下级, 不允许删除", typeName));
        }
    }
}
